/**************************
 * xxx 公司版权所有，未经同意，不可以随意复制、转发
 */
package edu.suda.xsap.security;

import com.codevip.tutorial.controller.common.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;

/******************************************
 * Jwt验证失败处理器
 *
 * @author yejf
 * @date 2023-11-29
 * @time 9:14
 * @package com.kclm.owep.web.security
 */
@Component
@Slf4j
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {
        log.debug("---> 进入AuthenticationEntryPoint的commence方法:"+authException);
        //
        response.setContentType("application/json;charset=UTF-8");
        //
        log.debug("===>{}",authException.getMessage());
        Result result = Result.failure("无Token信息或是Token已过期，请重新登录",request.getRequestURI());
        result.setCode(HttpServletResponse.SC_UNAUTHORIZED);

        //利用ObjectMapper转换成json发送到前端
        String json = objectMapper.writeValueAsString(result);
        //
        PrintWriter writer = response.getWriter();
        writer.print(json);
        //
        writer.flush();
        writer.close();
    }
}
